/*
 * @(#)Slot.java 1.0 2000/12/28
 * 
 * Copyright 2000 Thomas Barnekow. All Rights Reserved.
 * 
 * This software is the proprietary information of Thomas Barnekow. Use is
 * subject to license terms.
 */

package jessx.provider.jdbc;

import java.sql.*;

import jess.*;

import tb.provider.jdbc.*;
import jessx.provider.*;

/**
 * A {@link Slot}corresponding to a {@link Column}.
 * 
 * @author Thomas Barnekow
 * @version 1.0
 */
public class JdbcSlot extends Slot {

	public JdbcSlot(Column column, JdbcTemplate template)
		throws JessException {
		super(column.getName(), template);
		setDefaultValue(getDefaultValue(column));
		setTypeName(getTypeName(column));
	}

	/**
	 * Revisit! We don't currently support default values for OBJECT types.
	 */
	public static Value getDefaultValue(Column column) throws JessException {
		String defaultValue = column.getDefaultValue();
		if (defaultValue == null || defaultValue.equalsIgnoreCase("null"))
			return Funcall.NIL;

		String typeName = getTypeName(column);
		if (typeName.equals("STRING"))
			return new Value(defaultValue, RU.STRING);
		else if (typeName.equals("ATOM"))
			return new Value(defaultValue, RU.ATOM);
		else if (typeName.equals("INTEGER"))
			return new Value(
				Integer.valueOf(defaultValue).intValue(),
				RU.INTEGER);
		else if (typeName.equals("LONG"))
			return new LongValue(Long.valueOf(defaultValue).longValue());
		else if (typeName.equals("FLOAT"))
			return new Value(
				Double.valueOf(defaultValue).doubleValue(),
				RU.FLOAT);
		else
			// Revisit! This means we don't currently support default values
			// for
			// OBJECT types
			return Funcall.NIL;
	}

	/**
	 * Return Jess type name, i.e., STRING, INTEGER, FLOAT, LONG, and OBJECT.
	 * OBJECT means the default Java object type corresponding to the column's
	 * SQL type. See the JDBC Specification for details.
	 */
	public static String getTypeName(Column column) {
		switch (column.getDataType()) {
			case Types.CHAR :
			case Types.VARCHAR :
			case Types.LONGVARCHAR :
				return "STRING";
			case Types.NUMERIC :
			case Types.DECIMAL :
				if (column.getDecimalDigits() > 0) {
					if (column.getColumnSize() < 18)
						return "FLOAT";
					else
						return "OBJECT"; // i.e., java.math.BigInteger
				} else {
					if (column.getColumnSize() < 10)
						return "INTEGER";
					else if (column.getColumnSize() < 19)
						return "LONG";
					else
						return "OBJECT"; // i.e., java.math.BigInteger
				}
			case Types.BIT :
				return "ATOM";
			case Types.TINYINT :
			case Types.SMALLINT :
			case Types.INTEGER :
				return "INTEGER";
			case Types.BIGINT :
				return "LONG";
			case Types.REAL :
			case Types.FLOAT :
			case Types.DOUBLE :
				return "FLOAT";
			default :
				return "OBJECT";
		}
	}
}